<template lang="pug">
div
  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="按单出库")

      ScanSearch(
          placeholder="出库单号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )

      g-v.info(v-if="info")
        KvPair(v-if="info.OutputNo" k="单据号" :v="info.OutputNo")
        KvPair(v-if="info.AssemblyLine" k="车间编号" :v="info.AssemblyLine")
        KvPair(v-if="info.EWmNo" k="实体仓库" :v="info.EWmNo")
        KvPair(v-if="info.Dock" k="dock" :v="info.Dock")
        KvPair(
            v-if="info.RequestTime"
            k="需求时间"
            :v="info.RequestTime | Date"
            :kStyle="kvStyle.k"
            :vStyle="kvStyle.v"
            )

    InputTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :isLoading="isLoading"
        @check-input="checkInput"
        @click-row="clickRow"
        )

    g-h.bottom-bar(slot="fixed-bottom" j-c="space-around" v-if="info")
      Button(
          v-if="$root.User.permMap['SaveToPicking(按单出库)']"
          @click="pick"
          :text="pickButton.text"
          :disabled="pickButton.disabled"
          )
      Button(
          v-if="$root.User.permMap['SaveToOut(按单出库)']"
          @click="exportGoods"
          :text="exportButton.text"
          :disabled="exportButton.disabled"
          )
      Button(
          v-if="$root.User.permMap['SaveToFinish(按单出库)']"
          @click="save"
          :text="saveButton.text"
          :disabled="saveButton.disabled"
          )

</template>

<script>
import api from "$api"
import util from "$util"
import { mapState, mapGetters } from "vuex"

export default {
  data() {
    return {
      searchValue: "",
      isLoading: false,
      hasIllegalInput: false,

      clickableRow: {},

      loading: {
        search: false,
        pick: false,
        exportGoods: false,
        save: false,
      },

      pickButton: {
        text: "拣配",
        disabled: true,
      },
      exportButton: {
        text: "出库",
        disabled: true,
      },
      saveButton: {
        text: "完成",
        disabled: true,
      },

      headList: [
        { field: "WmNo", title: "库号", checked: true },
        { field: "PartNo", title: "物料号", checked: true },
        { field: "PartName", title: "物料名称", checked: true },
        { field: "PartSupplierNum", title: "供应商编号", checked: true },
        { field: "RequiredQty", title: "需求数量", checked: true },
        { field: "_realNum", title: "实际数量", checked: true },
        { field: "Location", title: "工位号", checked: true },
      ],

      kvStyle: {
        k: {
          width: "30%",
        },
        v: {
          width: "70%",
        },
      },
    }
  },
  computed: {
    ...mapState({
      info: state => state.deliverByOrder.info,
      body: state => state.deliverByOrder.body,
      partnoAndList: state => state.deliverByOrder.partnoAndList,
      active: state => state.deliverByOrder.active,
    }),
  },
  watch: {
    active(v) {
      // 切换tab时要重新绑定手机上的扫描键
      if (v === "ScanPage") {
        this.registerScanner()
        this.$forceUpdate()
      }
    },
  },
  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }
      // 重置所有状态
      this.$store.commit("deliverByOrder/reset")

      this.isLoading = true
      this.loading.search = true
      try {
        let data = await api.DeliverByOrderSearch({
          OutputNo: value,
        })
        this.reset()
        this.$store.commit("deliverByOrder/setInfo", {
          info: data.OutputInfo,
        })

        let inputRowList = [] // 可以输入的行
        // 检查状态
        // 根据规则给库存设置默认值
        if (data.OutputInfo.ConfirmFlag === 0) {
          let i = 0
          for (let item of data.OutputDetailInfo) {
            if (item.IsBatch === 0) {
              util.Alert(`物料[${item.PartNo}]的管理模式未维护,请维护库位与物料关系后操作`)
              return
            }
            if (item.IsBatch === 1) {
              inputRowList.push(i)
            }
            i++
          }
          if (inputRowList.length < i) {
            for (let item of data.OutputDetailInfo) {
              item._realNum = 0
            }
            for (let index of inputRowList) {
              data.OutputDetailInfo[index]._realNum = data.OutputDetailInfo[index].RequiredQty
            }
          } else {
            for (let item of data.OutputDetailInfo) {
              item._realNum = item.RequiredQty
            }

            this.pickButton.disabled = false
          }
        } else {
          for (let item of data.OutputDetailInfo) {
            item._realNum = item.RequiredQty
          }
        }

        let i = 0
        for (let item of data.OutputDetailInfo) {
          if (item.IsBatch === 2) {
            this.clickableRow[i] = true // 可以点击的行
          }
          i++
        }

        // 给可点击的行设置样式
        let styleMap = new Array(data.OutputDetailInfo.length)
        let firstField = this.headList[0].field
        for (let k in this.clickableRow) {
          styleMap[k] = {
            [firstField]: {
              color: "#1E88E5",
            }
          }
        }

        this.$store.commit("deliverByOrder/setBody", {
          body: {
            inputRowList,
            styleMap,
            list: data.OutputDetailInfo,
          },
        })

        switch (data.OutputInfo.ConfirmFlag) {
          case 0:
            this.pickButton.disabled = false
            break
          case 1:
             this.pickButton.text = "已拣配"
             this.exportButton.disabled = false
             break
           case 2:
             this.pickButton.text = "已拣配"
             this.exportButton.text = "已出库"
             this.saveButton.disabled = false
             break
           case 3:
             this.pickButton.text = "已拣配"
             this.exportButton.text = "已出库"
             this.saveButton.text = "已完成"
             break
        }
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    // 拣配
    async pick() {
      if (this.loading.pick) {
        return
      }
      if (this.pickButton.disabled) {
        return
      }
      if (this.hasIllegalInput) {
        util.Alert("输入框中包含不合法的数据")
        return
      }

      for (let item of this.body.list) {
        if (item.RequiredQty !== parseInt(item._realNum)) {
          util.Alert(`物料号为${item.PartNo}的物料数量与实际数量不等`)
          return
        }
      }

      let operType = "Batch"
      if (Object.keys(this.clickableRow).length > 0) {
        operType = "StorageToPick"
      }

      let bodyM = {}
      for (let item of this.body.list) {
        bodyM[item.PartNo] = item.WmNo
      }

      // 筛选出合格的电池
      let barcodeDetailList = []
      for (let k in this.partnoAndList) {
        let list = this.partnoAndList[k].barcodeList
        let statusMap = this.partnoAndList[k].statusMap
        for (let item of list) {
          if (statusMap[item.BarcodeData] === util.STATUS_OK) {
            item.TranNo = this.info.OutputNo
            item.WmNo = bodyM[item.PartNo]
            barcodeDetailList.push(item)
          }
        }
      }

      this.loading.pick = true
      try {
        let data = await api.DeliverByOrderPick({
          OutputId: this.info.OutputId,
          OperType: operType,
          barcodeDetailList,
        })
        this.pickButton.text = "已拣配"
        this.pickButton.disabled = true
        this.exportButton.disabled = false

        // 清除电池缓存数据
        this.$store.commit("deliverByOrder/clearBatteryCache")
        this.info.ConfirmFlag = 1
        this.$store.commit("deliverByOrder/setInfo", {
          info: this.info,
        })
        util.Toast("拣配成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.pick = false
      }
    },

    // 出库
    async exportGoods() {
      if (this.loading.exportGoods) {
        return
      }
      if (this.exportButton.disabled) {
        return
      }

      this.loading.exportGoods = true
      try {
        let data = await api.DeliverByOrderExport({
          OutputId: this.info.OutputId,
        })
        this.exportButton.text = "已出库"
        this.exportButton.disabled = true
        this.saveButton.disabled = false
        util.Toast("出库成功")
      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.exportGoods = false
      }
    },

    // 完成
    async save() {
      if (this.loading.save) {
        return
      }
      if (this.saveButton.disabled) {
        return
      }

      let operType = "Batch"
      for (let item of this.body.list) {
        if (item.IsBatch === 2) {
          operType = "StorageToOut"
          break
        }
      }

      this.loading.save = true
      util.Indicator.open()
      try {
        await api.DeliverByOrderSave({
          OutputId: this.info.OutputId,
          OutputNo: this.info.OutputNo,
          OutputDetailId: this.info.OutputDetailId,
          OperType: operType,
        })
        this.saveButton.text = "已完成"
        this.saveButton.disabled = true

        // 清除电池缓存数据
        this.$store.commit("deliverByOrder/clearBatteryCache")
        util.Indicator.close()
        util.Toast("完成成功")
      } catch(err) {
        util.Indicator.close()
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    // 重置本页的状态
    reset() {
      this.pickButton = {
        text: "拣配",
        disabled: true,
      }
      this.exportButton = {
        text: "出库",
        disabled: true,
      }
      this.saveButton = {
        text: "完成",
        disabled: true,
      }
    },

    // 检查输入数据
    checkInput(v) {
      if (v == null || v === "") {
        return
      }
      let isNatural = /^(0|[1-9]\d*)$/.test(v)
      if (!isNatural) {
        this.hasIllegalInput = true
        util.Toast(`错误的输入: ${v}`)
      } else if (this.hasIllegalInput) {
        this.hasIllegalInput = false
      }
    },

    // 点击行转到扫电池页面
    clickRow(row, index) {
      if (this.clickableRow[index]) {
        this.$store.commit("deliverByOrder/switchToBarcode", {
          index,
        })
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },
  },

  created() {
    this.registerScanner()
  },
}
</script>

<style lang="stylus" scoped>

.info
  border: 1px solid grey200

.table
  scan-table()

.bottom-bar
  bottom: 10rem
  bottom-bar()

</style>
